<?php namespace App\Http\Controllers\Admin;

use App\Category;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Job;
use App\Region;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ProductController extends Controller
{
    public function getTypes($id = 0)
    {
        if(1 == $id){
            $list = Category::where('rank', '1')->paginate(config('site.admin.pageSize'));
        } else {
            $list = Category::where('rank', '2')->paginate(config('site.admin.pageSize'));
        }
        if (Cache::has('parent') && 1 == 2) {
            $parent = Cache::get('parent');
        } else {
            $parent = Category::where('rank', '1')->lists('name', 'categoryid');
            Cache::forever('parent', $parent);
        }
        return view('admin.products.types', [
            'list' => $list,
            'parent' => $parent,
        ]);
    }

    public function getNewt($id = 0)
    {
        $model = Category::findOrNew($id);
        if (Cache::has('parent')) {
            $parents = Cache::get('parent');
        } else {
            $parents = Category::where('rank', '1')->lists('name', 'categoryid');
            Cache::forever('parent', $parents);
        }
        return view('admin.products.newt', [
            'model' => $model,
            'parents' => $parents,
        ]);
    }

    public function postNewt(Request $request, $id = 0)
    {
        $data = $request->all();
        $rules = [
            "name" => "required",
            "parentid" => "required|numeric",
            "isShow" => "required|boolean"
        ];
        $attributes = [
            "name" => "类别名称",
            "parentid" => "父级类别",
            "isShow" => "是否启用"
        ];
        $message = [
            "required" => ":attribute不能为空",
            "unique" => ":attribute已被使用",
            "numeric" => "请选择正确的父级分类",
            "boolean" => "请选择正确的状态",
        ];
        $validator = \Validator::make($data, $rules, $message, $attributes);
        if ($validator->fails()) {
            $ret = ['state' => 'fail'];
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        } else {
            $data['rank'] = 2;
            $data['updateDate'] = date("Y-m-d H:i:s");
            $model = Category::findOrNew($id);
            if($model->rank == 1){
                unset($data['rank']);
                unset($data['parentid']);
            }
            if (0 == $id) {
                $last = Category::where('parentid', $data['parentid'])->orderBy('categoryid', 'DESC')->select('categoryid')->first();
                $model->categoryid = intval($last['categoryid'] + 1);
                $data['inputDate'] = $data['updateDate'];
            }
            $model->fill($data);
            $model->save();//写入数据库
            $ret = ['state' => 'success', 'message' => '操作成功'];
            return \Response::json($ret);
        }
    }

    public function anyDelt($id)
    {
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        if (Category::destroy($id)) {
            $ret = ['state' => 'success', 'message' => '删除成功'];
        }
        return \Response::json($ret);
    }

    public function getIndex(Request $request)
    {
        $appends = $request->all();
        $users = User::orderBy('name')->lists('nick', 'id');
        $list = Job::orderBy('pubtime', 'DESC');
        if (isset($appends['name']) && "" != $appends['name']) {
            $list = $list->where('name', 'like', '%' . $appends['name'] . '%');
        }
        if (isset($appends['parentcategory']) && "" != $appends['parentcategory']) {
            $list = $list->where('parentcategory', $appends['parentcategory']);
        }
        if (isset($appends['userid']) && "" != $appends['userid']) {
            $list = $list->where('userid', 'like', $appends['userid']);
        }
        $list = $list->paginate(config('site.admin.pageSize'));
        if (Cache::has('parent') && 1 == 2) {
            $parent = Cache::get('parent');
        } else {
            $parent = Category::where('rank', '1')->lists('name', 'categoryid');
            Cache::forever('parent', $parent);
        }
        $categorys = Category::where('rank', '2')->where('isShow',1)->lists('name','categoryid');
        return view('admin.products.index', [
            'list' => $list,
            'parent' => $parent,
            'users' => $users,
            'appends' => $appends,
            'categorys' => $categorys,
        ]);
    }

    public function getNewj($id = 0)
    {
        $model = Job::findOrNew($id);
        if (Cache::has('parent') && 1 == 2) {
            $parent = Cache::get('parent');
        } else {
            $parent = Category::where('rank', '1')->lists('name', 'categoryid');
            Cache::forever('parent', $parent);
        }
        $categorys = Category::where('rank', '2')->where('isShow',1)->get();
        return view('admin.products.newj', [
            'model' => $model,
            'parents' => $parent,
            'categorys' => $categorys,
        ]);
    }

    public function postNewj(Request $request, $id = 0)
    {
        $model = Job::findOrNew($id);
        $data = $request->all();
        $rules = [
            "name" => "required",
            "imgurl" => "required",
            "parentcategory" => "required",
            "categoryid" => "required",
            "endtime" => "required",
            "starttime" => "required",
            "addr" => "required",
            "describe" => "required",
        ];
        $attributes = [
            "name" => "名称",
            "imgurl" => "显示图片",
            "parentcategory" => "分类",
            "categoryid" => "分类",
            "starttime" => "开工时间",
            "endtime" => "结束时间",
            "addr" => "地址",
            "describe" => "描述",
        ];
        $validator = \Validator::make($data, $rules, ['required' => ':attribute不能为空'], $attributes);
        if ($validator->fails()) {
            $ret = ['state' => 'fail'];
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        } else {
            if (Cache::has('parent') && 1 == 2) {
                $parent = Cache::get('parent');
            } else {
                $parent = Category::where('rank', '1')->lists('name', 'categoryid');
                Cache::forever('parent', $parent);
            }
            $categorys = Category::find($data['categoryid']);
            $data['parentkind'] = $parent[$data['parentcategory']];
            $data['kind'] = $categorys->name;
            $data['pubtime'] = isset($model->pubtime) ? $model->pubtime : date("Y-m-d H:i:s");
            if ("" == $data['discount']) {
                unset($data['discountunit']);
            }
            if (!$model->jobid) {
                $model->userid = \Auth::user()->id;
            }
            $model->fill($data);
            $model->save();//写入数据库
            if ($model->jobid) {
                $ret = ['state' => 'success', 'message' => '操作成功'];
            } else {
                $ret = ['state' => 'fail'];
                $ret['message'] = '保存出错';
            }
        }
        return $ret;
    }

    public function getDelj($id = 0)
    {
        $model = Job::findOrNew($id);
        return view('admin.products.delj', [
            'model' => $model,
        ]);
    }

    public function postDelj(Request $request, $id = 0)
    {
        $model = Job::findOrNew($id);
        $data = $request->all();
        $model->reason = $data['reason'];
        $model->canceltime = date("Y-m-d H:i:s");
        $model->state = '已取消';
        $model->save();
        if ($model->jobid) {
            $ret = ['state' => 'success', 'message' => '操作成功'];
        } else {
            $ret = ['state' => 'fail'];
            $ret['message'] = '删除失败';
        }
        return \Response::json($ret);
    }

    public function getRegion(Request $request)
    {
        $list = Region::orderBy('superiorRegion', 'DESC');
        $appends = $request->all();
        if (isset($appends['title']) && "" != $appends['title']) {
            $list = $list->where('regionName', 'like', '%' . $appends['title'] . '%');
        }
        $list = $list->paginate(config('site.admin.pageSize'));
        return view('admin.products.region', [
            'list' => $list,
            'appends' => $appends,
        ]);
    }

    public function getNewr($id = 0)
    {
        $model = Region::findOrNew($id);
        if (Cache::has('region')) {
            $region = Cache::get('region');
        } else {
            $region = Region::where('memo', '启用')->where("superiorRegion", 0)->lists('regionName', 'sysRegionId');
            Cache::forever('region', $region);
        }
        return view('admin.products.newr', [
            'model' => $model,
            'regions' => $region
        ]);
    }

    public function postNewr(Request $request, $id = 0)
    {
        $data = $request->all();
        if ("" == $data['regionName']) {
            $ret = ['state' => 'fail', 'message' => '名称不能为空'];
        } else {
            unset($data['_token']);
            if(isset($data['child']) && $data['child'] == 0) unset($data['child']);
            $model = Region::findOrNew($id);
            if("" == $model->sysRegionId){
                $data['inputDate'] = date("Y-m-d H:i:s");
                $data['inputMan'] = \Auth::user()->nick;
            }
            $model->fill($data);
            $model->save();
            if ($model->sysRegionId) {
                $ret = ['state' => 'success', 'message' => '操作成功'];
            } else {
                $ret = ['state' => 'fail'];
                $ret['message'] = '删除失败';
            }
            return \Response::json($ret);
        }
    }

    public function anyDelr($id)
    {
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        $hasson = Region::where('superiorRegion',$id)->first();
        if([] != $hasson){
            $ret = ['state' => 'fail', 'message' => '此城市包含子城市，无法删除！'];
        } else {
            if (Region::destroy($id)) {
                $ret = ['state' => 'success', 'message' => '删除成功'];
            }
        }
        return \Response::json($ret);
    }

    public function __destruct()
    {
        Cache::flush();
    }
}